package com.atguigu.common.utils;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.LoginUserVo;
import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    /**
     * token过期时间,单位秒
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;

    /**
     * 加密的秘钥
     */
    private static final String SECRET = "gulimall@hupp";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "GL";

    /**
     * subject
     */
    private static final String SUBJECT = "gulimall-user";


    /**
     * 创建token
     *
     * @param userVo
     * @return
     */
    public static String getJwtToken(LoginUserVo userVo) {
        String token = Jwts.builder()
                //设置token的头部分
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256")

                //设置过期时间
                .setSubject(SUBJECT)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                //设置主体部分
                /*.claim("id", id)
                .claim("userName", userName)
                .claim("mobile", mobile)*/
                .claim(AuthServerConstant.LOGIN_USER, userVo)

                .signWith(SignatureAlgorithm.HS256, SECRET).compact(); //指定算法为HS256

        //拼装，进行业务区分
        token = TOKEN_PREFIX + token;
        return token;
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) return false;
        try {
            final Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replaceFirst(TOKEN_PREFIX, "")).getBody();

            return true;

        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取token中的用户数据
     *
     * @param request
     * @param key
     * @return
     */
    public static LoginUserVo getUser(HttpServletRequest request, String key) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) return null;

        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replaceFirst(TOKEN_PREFIX, ""));
            if (claimsJws != null) {
                Object o = claimsJws.getBody().get(key);
                LoginUserVo userVo = JSON.parseObject(JSON.toJSONString(o), LoginUserVo.class);
                return userVo;
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}